<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理内容 -->
      <div class="role-operate">
        <el-button size="small" type="primary" @click="showDialog=true">添加角色</el-button>
      </div>
      <el-table :data="roleTableData">
        <el-table-column prop="id" width="100" align="center" label="序号" />
        <el-table-column prop="name" width="200" align="center" label="角色">
          <template v-slot="{row}">
            <el-input v-if="row.isEdit" v-model="row.editrow.name" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" width="200" align="center" label="启用">
          <!-- 自定义列结构 -->
          <template #default="{row}">
            <el-switch v-if="row.isEdit" v-model="row.editrow.state" :active-value="1" :inactive-value="0" />
            <span v-else>{{ row.state===1?"已启用":row.state===0?"未启用":"无" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" align="center" label="描述">
          <template v-slot="{row}">
            <el-input v-if="row.isEdit" v-model="row.editrow.description" type="textarea" size="small" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <!-- 放置操作按钮 -->
          <template v-slot="{row}">
            <template v-if="row.isEdit">
              <!-- 放置编辑状态 -->
              <el-button size="small" type="primary" @click="btnEditOk(row)">确定</el-button>
              <el-button size="small" @click="row.isEdit=false">取消</el-button>
            </template>
            <template v-else>
              <el-button type="text" @click="btnAssign(row.id)">分配权限</el-button>
              <el-button type="text" @click="btnEditRow(row)">编辑</el-button>
              <el-popconfirm title="确定删除该角色吗？" @onConfirm="confirmDel(row.id)">
                <el-button slot="reference" style="margin-left:10px;" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <!-- 放置分页组件 -->
      <el-row style="height:60px;" type="flex" align="middle" justify="end">
        <el-pagination
          :current-page="pageParams.page"
          :page-size="pageParams.pagesize"
          :total="pageParams.total"
          layout="prev, pager, next"
          @current-change="changePage"
        />
      </el-row>
    </div>
    <!-- 放置 添加和编辑弹层 -->
    <el-dialog width="500px" title="新增角色" :visible.sync="showDialog" class="dialog-container" @close="close">
      <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="120px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" style="width:300px" />
        </el-form-item>
        <!-- 重置表单需要prop -->
        <el-form-item label="启用" prop="state">
          <el-switch v-model="roleForm.state" active-value="1" inactive-value="0" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="roleForm.description" type="textarea" :rows="3" style="width:300px" />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="24">
              <el-button size="small" type="primary" @click="btnSure">确定</el-button>
              <el-button size="small" @click="btnCancel">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 放置分配权限弹层 -->
    <el-dialog :visible.sync="showPermissionDialog" title="分配权限">
      <el-tree
        ref="permTree"
        :data="permissionList"
        :props="{label:'name'}"
        default-expand-all
        show-checkbox
        node-key="id"
        :default-checked-keys="permIds"
        check-strictly
      />
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="4">
          <el-button size="small" type="primary" @click="btnAllot">确定</el-button>
          <el-button size="small" @click="btnAllotCancel">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { _addRole, _allotRole, _deleteRole, _getRoleDetail, _getRoleList, _updateRole } from '@/api/role'
import { _getPermissionList } from '@/api/permission'
import { tranListToTreeData } from '@/utils/index'
export default {
  name: 'Role',
  data() {
    return {
      permIds: [],
      currentId: null,
      permissionList: [],
      showPermissionDialog: false,
      showDialog: false,
      roleTableData: [],
      pageParams: {
        page: 1, // 第几页
        pagesize: 5, // 每页多少条
        total: 0 // 角色总数
      },
      roleForm: {
        name: '',
        description: '',
        state: 0
      },
      rules: {
        name: [{ required: true, trigger: 'blur', message: '角色名称不能为空' }],
        description: [{ required: true, trigger: 'blur', message: '角色描述不能为空' }]
      }
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const { rows, total } = await _getRoleList(this.pageParams)
      this.roleTableData = rows
      this.pageParams.total = total
      this.roleTableData.forEach(item => {
        // 添加一个属性isEdit为false
        // item.isEdit = false
        // 在赋值后动态添加的属性 不具备响应式的特征
        // this.$set(目标对象,属性名称,初始值) 可以针对目标对象 添加的属性 添加响应式
        this.$set(item, 'isEdit', false)
        this.$set(item, 'editrow', {
          name: item.name,
          description: item.description,
          state: item.state
        })
      })
    },
    // newPage作为回调函数参数
    changePage(newPage) {
      this.pageParams.page = newPage
      this.getRoleList()
    },
    close() {
      this.$refs.roleForm.resetFields()
    },
    btnSure() {
      this.$refs.roleForm.validate(async valid => {
        if (valid) {
          await _addRole(this.roleForm)
          this.$message.success('新增角色成功')
          this.getRoleList()
          this.btnCancel()
        }
      })
    },
    btnCancel() {
      this.showDialog = false
      this.close()
    },
    btnEditRow(row) {
      // console.log(row)
      row.isEdit = true
      row.editrow.name = row.name
      row.editrow.state = row.state
      row.editrow.description = row.description
    },
    async btnEditOk(row) {
      if (row.editrow.name && row.editrow.description) {
        // alert('这里可以')
        await _updateRole({ ...row.editrow, id: row.id })
        this.$message.success('更新角色成功')
        // row.name = row.editrow.name eslint校验不通过,可能会有错误
        // Object.assign(target,source)
        Object.assign(row, {
          ...row.editrow,
          isEdit: false
        })
      } else {
        this.$message.warning('角色和描述不能为空')
      }
    },
    async confirmDel(id) {
      // alert(111)
      await _deleteRole(id)
      this.$message.success('删除角色成功')
      if (this.roleTableData.length === 1) {
        this.pageParams.page--
      }
      this.getRoleList()
    },
    async btnAssign(id) {
      const { permIds } = await _getRoleDetail(id)
      this.permIds = permIds
      this.permissionList = tranListToTreeData(await _getPermissionList(), 0)
      // console.log(this.permissionList)
      this.currentId = id
      this.showPermissionDialog = true
    },
    async btnAllot() {
      await _allotRole({ id: this.currentId, permIds: this.$refs.permTree.getCheckedKeys() })
      this.$message.success('角色分配权限成功')
      this.btnAllotCancel()
    },
    btnAllotCancel() {
      this.showPermissionDialog = false
    }
  }
}
</script>
<style scoped>
.role-operate{
  padding: 10px;
}
.container .dialog-container .el-button{
  margin:0 30px;
}
</style>
